from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import Ui_bankEdit
import master.utility as utility

class BankAccEdit(QDialog, Ui_bankEdit.Ui_bankEditDlg):
    
  StyleSheet = """
QLineEdit[mandatory="true"] {
    background-color: rgb(255, 255, 127);
    color: darkblue;
}
"""

  def __init__(self, dbConn, tipe,  dataGlob, parent=None):
        super(BankAccEdit, self).__init__(parent)
        self.setupUi(self)
        self.db = dbConn
        self.tipe = tipe
        self.dataGlob = dataGlob
        self.util = utility.Utility(self.db)
        self.initData()
        
        self.mastModel = QSqlTableModel(self)
        self.mastModel.setTable("bank_acc")
        self.mastModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        
        self.idModel = QSqlTableModel(self)
        self.idModel.setTable("master_nodok")
        self.idModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        
        self.lineedits = (self.name_le, self.acc_le,  self.coa_le)
        for lineEdit in self.lineedits:
            lineEdit.setProperty("mandatory", QVariant(True))
        self.setStyleSheet(BankAccEdit.StyleSheet)
        
  @pyqtSignature("")
  def on_save_pb_clicked(self):
      if self.tipe == "add":
          if self.tambahData():
              self.close()
          else:
              QMessageBox.warning(self, "Bank Account","Can not add new data.")
      else:
          if self.updateData():
              self.close()
          else:
              QMessageBox.warning(self, "Bank Account","Can not update data")
      
  @pyqtSignature("")
  def on_cancel_pb_clicked(self):
      self.close()

  def tambahData(self):
      if not self.validasi():
          return
      self.mastModel.select()  
      hari = self.util.getServerToday() 
      self.time_le.setDateTime(hari)
      self.id_le.setText(self.idBaru())
      QSqlDatabase.database().transaction()
      if not self.mastModel.insertRow(0):
          return
      self.mastModel.setData(self.mastModel.index(0, 0), QVariant(self.id_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 1), QVariant(self.name_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 2), QVariant(self.acc_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 3), QVariant(self.note_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 4), QVariant(self.code_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 5), QVariant(self.coa_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 6), QVariant(self.user_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 7), QVariant(self.time_le.dateTime()))
      self.mastModel.setData(self.mastModel.index(0, 8), QVariant(self.owner_le.text()))
      if not self.mastModel.submitAll():
          return
      if not QSqlDatabase.database().commit():
          return
      return True

  def updateData(self):
      if not self.validasi():          
          return
      self.mastModel.setFilter("bank_id = '"+self.tipe+"'")
      self.mastModel.select()      
      QSqlDatabase.database().transaction()
      self.mastModel.setData(self.mastModel.index(0, 1), QVariant(self.name_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 2), QVariant(self.acc_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 3), QVariant(self.note_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 4), QVariant(self.code_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 5), QVariant(self.coa_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 8), QVariant(self.owner_le.text()))
      if not self.mastModel.submitAll():
          return
      if not QSqlDatabase.database().commit():
          return
      return True

  def initData(self):
      self.user_le.setText(self.dataGlob["nama"])
      if self.tipe != "add":
          query = QSqlQuery(self.db)
          qStr = "select bank_id, nama, no_acc, ket, kode, kode_coa, audit_user, audit_time, nama_owner from bank_acc where bank_id = '"+self.tipe+"'"
          query.exec_(qStr)
          query.next()
          self.id_le.setText(unicode(query.value(0).toString()))
          self.name_le.setText(unicode(query.value(1).toString()))
          self.acc_le.setText(unicode(query.value(2).toString()))
          self.note_le.setText(unicode(query.value(3).toString()))
          self.code_le.setText(unicode(query.value(4).toString()))
          self.coa_le.setText(unicode(query.value(5).toString()))
          self.user_le.setText(unicode(query.value(6).toString()))
          self.time_le.setDateTime(query.value(7).toDateTime())
          self.owner_le.setText(unicode(query.value(8).toString()))
          
  def idBaru(self):
      noAkhir = 0
      query = QSqlQuery(self.db)
      kode = "BAC"
      per = self.util.getServerToday().date().toString("MMyy")
      self.idModel.setFilter("kode_dok = '"+kode+"' and periode = '"+per+"'")
      self.idModel.select()      
      class DatabaseError(Exception): pass
      rback = False
      try:
          if not QSqlDatabase.database().transaction():
              raise DatabaseError
          rback = True
          if self.idModel.rowCount() == 1:
              record = self.idModel.record(0)
              noAkhir = record.value(2).toInt()[0]
              noAkhir += 1
              self.idModel.setData(self.idModel.index(0, 2), QVariant(noAkhir))
          else:
              self.idModel.insertRow(0)
              self.idModel.setData(self.idModel.index(0, 0), QVariant(kode))
              self.idModel.setData(self.idModel.index(0, 1), QVariant(per))
              self.idModel.setData(self.idModel.index(0, 2), QVariant("1"))
              self.idModel.setData(self.idModel.index(0, 3), QVariant("bank_acc"))
              noAkhir = 1
          self.idModel.submitAll()
          if not QSqlDatabase.database().commit():
            raise DatabaseError
          rback = False
      finally:
          if rback:
              if not QSqlDatabase.database().rollback():
                  raise DatabaseError
      id = kode+per+"0"*(4 - len(str(noAkhir)))+str(noAkhir)
      return id
      
  def validasi(self):
      valid = True
      for lineEdit in self.lineedits:
           if lineEdit.text().isEmpty():
               QMessageBox.warning(self, "Bank Account","Please cek mandatory column (Yellow background)")
               return False
      return valid

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = BankAccEdit()
    form.show()
    app.exec_()
